local gotQuests = gotQuests

local locAutoComplete

local QuestTitleMatch_LowLevel = TRIVIAL_QUEST_DISPLAY:gsub("([%(%)])", "%%%1"):gsub("%%s", "(.+)")
local function ChangeQuestIcons(self, event)
	buttonName = event and "GossipTitleButton" or "QuestTitleButton"
	iconName = event and "GossipIcon" or "QuestIcon"
	local forLimit = event and GossipFrame.buttonIndex or GetNumActiveQuests() + GetNumAvailableQuests()
	for i=1, forLimit do
		button = _G[buttonName..i]
		if button:IsShown() then
			local name = button:GetText()
			if name then
				name = name:match(QuestTitleMatch_LowLevel) or name:sub(11, -3)
				if button.type == "Available" or button.isActive == 0 then
					if locAutoComplete[name] and locAutoComplete[name].autoAccept then
						return button:Click()
					end
				elseif button.type == "Active" or button.isActive == 1 then
					local index = gotQuests:GetQuestLogIndexByName(name)
					if index then
						if select(7, GetQuestLogTitle(index)) then
							-- This is for low level quests, to stop them being greyed out when completed.
							_G[button:GetName()..iconName]:SetVertexColor(1,1,1)
							if locAutoComplete[name] and locAutoComplete[name].autoComplete then
								return button:Click()
							end
						else
							_G[button:GetName()..iconName]:SetTexture("Interface\\AddOns\\gotQuests\\GreyActiveQuestIcon")
						end
					end
				end
			end
		end
	end
end

gotQuests:RegisterEvent("GOSSIP_SHOW", ChangeQuestIcons)
QuestFrameGreetingPanel:HookScript("OnShow", ChangeQuestIcons)

-- Accept at QUEST_DETAIL
gotQuests:RegisterEvent("QUEST_DETAIL", function(self)
	if locAutoComplete[GetTitleText()] and locAutoComplete[GetTitleText()].autoAccept then
		AcceptQuest()
	end
end)

local awaitingSelection
-- Auto-pick reward.
gotQuests:RegisterEvent("QUEST_COMPLETE", function(self)
	local data = locAutoComplete[GetTitleText()]
	if data and data.autoComplete then
		local numQuestChoices = GetNumQuestChoices()
		local choice
		if numQuestChoices > 0 then
			local autoCompleteType = type(data.autoComplete)
			if autoCompleteType == "string" then
				local name, texture, numItems, quality, isUsable
				for i=1, GetNumQuestChoices() do
					name, texture, numItems, quality, isUsable = GetQuestItemInfo("choice", i)
					if name == data.autoComplete then
						choice = i
						break
					end
				end
			end
			
			if autoCompleteType == "boolean" or not choice then
				awaitingSelection = GetTitleText()
				return print("Please select a reward and click complete quest.")
			end
		end

		GetQuestReward(choice)
	end
end)

hooksecurefunc("QuestRewardCompleteButton_OnClick", function(self)
	if awaitingSelection == GetTitleText() and QuestFrameRewardPanel.itemChoice > 0 then
		locAutoComplete[awaitingSelection].autoComplete = GetQuestItemInfo("choice", QuestFrameRewardPanel.itemChoice)
		print("Saving %s as desired reward for %q.", awaitingSelection, GetQuestItemInfo("choice", QuestFrameRewardPanel.itemChoice))
		awaitingSelection = nil
	end
end)

-- Click through QUEST_PROGRESS screens.
QuestFrameProgressPanel:HookScript("OnShow", function()
	if IsQuestCompletable() and locAutoComplete[GetTitleText()] and locAutoComplete[GetTitleText()].autoComplete then
		CompleteQuest()
	end
end)

local on, off = "(|cff00ff00On|r)", "(|cffff0000Off|r)"
local function LearnAutoComplete(autoAccept, autoComplete)
	local choiceIndex = QuestFrameRewardPanel.itemChoice
	if not choiceIndex then
		local focus = GetMouseFocus()
		if focus:GetName() then
			choiceIndex = tonumber(focus:GetName():match("QuestDetailItem(%d+)"))
		end
	end
	local item
	if choiceIndex and choiceIndex > 0 and choiceIndex <= GetNumQuestChoices() then 
		item = GetQuestItemInfo("choice", choiceIndex)
	elseif GetNumQuestChoices() > 0 and autoComplete then
		if QuestFrameRewardPanel:IsShown() then
			return print("Please select a reward and run /gqlearn again.")
		else
			return print("Please mouseover a reward and run /gqlearn again.")
		end
	end
	local questName = GetTitleText()
	
	if questName and questName ~= "" then
		local t = locAutoComplete[questName] or {}
		t.autoAccept = autoAccept
		t.autoComplete = item or autoComplete
		locAutoComplete[questName] = t
		
		print(format("Watching %q: Auto-Accept %s - Auto-Complete %s", questName, autoAccept and on or off, autoComplete and (item and on.." with item: "..item or on) or off))
	end
end

gotQuests:RegisterEvent("ADDON_LOADED", function(self, event, addon)
	if addon == "gotQuests" then
		if not gotQuestsDB then
			gotQuestsDB = {}
		end
		
		if not gotQuestsDB.AutoCompleteList then
			gotQuestsDB.AutoCompleteList = {}
		end
		
		locAutoComplete = gotQuestsDB.AutoCompleteList
	end
end)

SlashCmdList["GQ_Learn"] = function(cmd)
	cmd = cmd:lower()
	local noAccept, noComplete = cmd:find("noaccept"), cmd:find("nocomplete")
	LearnAutoComplete(not noAccept, not noComplete)
end
SLASH_GQ_Learn1 = "/gqlearn"